//
//  ReviewOrderDetailsViewController.m
//  OrderAssistant
//
//  Created by chendong on 2020/10/28.
//  Copyright © 2020 chendong. All rights reserved.
//

#import "ReviewOrderDetailsViewController.h"
#import "ReviewOrderDetailsTableViewCell.h"
#import "NetTools.h"
#import <SVProgressHUD.h>
#import "FCUUID.h"
#import <AFNetworking.h>
@interface ReviewOrderDetailsViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>{
    UIAlertView *a1;
}
@property(nonatomic,strong) UITableView *myTableView;
@property(nonatomic,strong) NSMutableArray *myTableViewArr;

@end

@implementation ReviewOrderDetailsViewController
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView == a1) {
        if (buttonIndex == 1) {
            [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeClear];
            NSDictionary *dic = @{
                @"strUserId":[NSString stringWithFormat:@"%@",self.userData[@"UserID"]],
                @"strUserName":[NSString stringWithFormat:@"%@",self.userData[@"UserName"]],
                @"strOrderID":[NSString stringWithFormat:@"%@",self.dic[@"OrderID"]]
            };
            NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"ipaddress"];
            [NetTools postWithUrl:[NSString stringWithFormat:@"http://%@/ldcy/OrderGoods/OrderGoods.asmx/ReviewOrder",str] pararms:dic
             success:^(id  _Nonnull json) {
                [SVProgressHUD dismiss];
                if ([[NSString stringWithFormat:@"%@",json[@"IsResult"]] isEqualToString:@"1"]) {
                    UIAlertView *a = [[UIAlertView alloc]initWithTitle:@"审核成功" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [a show];
                }else{
                    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                    [SVProgressHUD setMinimumDismissTimeInterval:0.2f];
                    [SVProgressHUD showImage:[UIImage imageNamed:@""] status:[NSString stringWithFormat:@"%@",json[@"Message"]]];
                }
            } fail:^(NSError * _Nonnull error) {
                NSData * data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
                NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"服务器的错误原因:%@",str);
                [SVProgressHUD dismiss];
            }];
        }
    }else{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"shenhe" object:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }
}
-(NSMutableArray *)myTableViewArr{
    if (!_myTableViewArr) {
        _myTableViewArr = [[NSMutableArray alloc]init];
    }
    return _myTableViewArr;
}
-(UITableView *)myTableView{
    if (!_myTableView) {
        _myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT-100) style:UITableViewStylePlain];
        _myTableView.dataSource = self;
        _myTableView.delegate = self;
//        _myTableView.backgroundColor = [UIColor blueColor];
        [self.view addSubview:_myTableView];
    }
    return _myTableView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = [NSString stringWithFormat:@"未审核订单详情(%@)",self.dic[@"Warehouse"]];
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIView *leftV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    UIButton *gwcBtnl = [UIButton buttonWithType:UIButtonTypeCustom];
    gwcBtnl.frame = CGRectMake(0, 5, 30, 30);
    gwcBtnl.userInteractionEnabled = NO;
    [gwcBtnl setImage:[UIImage imageNamed:@"货框_03.png"] forState:UIControlStateNormal];
    gwcBtnl.imageView.contentMode = UIViewContentModeScaleAspectFit;
    UITapGestureRecognizer *t = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(leftAction:)];
    [leftV addGestureRecognizer:t];
    [leftV addSubview:gwcBtnl];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftV];
    
//    [self myTableView];
    UIView *bottomBGV = [[UIView alloc]initWithFrame:CGRectMake(0, SCREENHEIGHT-kTabBarHeight-20, SCREENWIDTH, kTabBarHeight+20)];
    bottomBGV.backgroundColor = RGBCOLOR(235, 235, 235);
    [self.view addSubview:bottomBGV];
    UIButton *xdBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    xdBtn.frame = CGRectMake(10, 15, bottomBGV.frame.size.width-20, 40);
    xdBtn.layer.cornerRadius = 5;
    xdBtn.layer.borderWidth = 1;
    xdBtn.layer.borderColor = RGBCOLOR(108, 185, 252).CGColor;
    xdBtn.backgroundColor = RGBCOLOR(108, 185, 252);
    [xdBtn setTitle:@"审核" forState:UIControlStateNormal];
    [xdBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [bottomBGV addSubview:xdBtn];
    [xdBtn addTarget:self action:@selector(xdBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self getData];
}

-(void)xdBtnAction:(UIButton *)btn{
    a1 = [[UIAlertView alloc] initWithTitle:@"确定审核么？" message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    a1.delegate = self;
    [a1 show];
}
-(void)leftAction:(UITapGestureRecognizer *)item{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)getData{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeClear];
    NSDictionary *dic = @{
        @"strOrderId":[NSString stringWithFormat:@"%@",self.dic[@"OrderID"]],
        @"strGroup":@"0"
    };
    NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"ipaddress"];
    if (str.length == 0) {
        // 请求头
//        NSString *accessPath = @"http://192.168.0.19:80/Api/OrderGoods/GetOrderDetails";
        NSString *accessPath = @"http://crm.zhenyea.com/Api/OrderGoods/GetOrderDetails";
        // 请求参数字典
        NSDictionary *params = @{
            @"strOrganizationNo":[NSString stringWithFormat:@"%@",self.userData[@"OrganizationNo"]],
            @"strOrderID":[NSString stringWithFormat:@"%@",self.dic[@"OrderID"]],
            @"strUserId":[NSString stringWithFormat:@"%@",self.userData[@"UserID"]],
            @"strPassword":[NSString stringWithFormat:@"%@",self.userData[@"UserPass"]],
            @"strIMEI":[FCUUID uuidForVendor],
            @"strGroup":@"0"
        };
        
        //创建配置信息
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        //设置请求超时时间：5秒
        configuration.timeoutIntervalForRequest = 5;
        //创建会话
        NSURLSession *session = [NSURLSession sessionWithConfiguration: configuration delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
        NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",accessPath]]];
        //设置请求方式：POST
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"content-Type"];
        [request setValue:@"application/json;charset=gb2312" forHTTPHeaderField:@"Accept"];
        
        //data的字典形式转化为data
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
        //设置请求体
        [request setHTTPBody:jsonData];
        
        NSURLSessionDataTask * dataTask =[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            [SVProgressHUD dismiss];
            if (error == nil) {
                NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
                NSString *receiveStr = [[NSString alloc]initWithData:data encoding:encoding];
                NSData * aData = [receiveStr dataUsingEncoding:NSUTF8StringEncoding];
                NSError *errorr = nil;
                id response = [NSJSONSerialization JSONObjectWithData:aData options:NSJSONReadingMutableContainers error:&errorr];
                if ([response isKindOfClass:[NSDictionary class]]) {
                    // 请求成功数据处理
                    NSString *IsResult = [NSString stringWithFormat:@"%@",[response objectForKey:@"IsResult"]];
                    if ([IsResult isEqualToString:@"1"]) {
                        NSArray *a = response[@"Data"];
                        self.myTableViewArr = [a mutableCopy];
                        [self.myTableView reloadData];
                    }else{
                        [SVProgressHUD setMinimumDismissTimeInterval:0.2f];
                        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:[NSString stringWithFormat:@"%@",response[@"Message"]]];
                    }
                } else {

                }
            }else{
                NSLog(@"error===%@",error);
            }
        }];
        [dataTask resume];

//        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//
//        NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:accessPath parameters:params error:nil];
//        request.timeoutInterval = 10.f;
//        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
//
//        NSURLSessionDataTask *task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
//            [SVProgressHUD dismiss];
//            if (!error) {
//                if ([responseObject isKindOfClass:[NSDictionary class]]) {
//                    // 请求成功数据处理
//                    NSString *IsResult = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"IsResult"]];
//                    if ([IsResult isEqualToString:@"1"]) {
//                        NSArray *a = responseObject[@"Data"];
//                        self.myTableViewArr = [a mutableCopy];
//                        [self.myTableView reloadData];
//                    }else{
//                        [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
//                        [SVProgressHUD setMinimumDismissTimeInterval:0.2f];
//                        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:[NSString stringWithFormat:@"%@",responseObject[@"Message"]]];
//                    }
//                } else {
//
//                }
//            } else {
//                NSData * data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
//                NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//                NSLog(@"服务器的错误原因:%@",str);
//                [SVProgressHUD dismiss];
//            }
//        }];
//
//        [task resume];
    }else{
        [NetTools postWithUrl:[NSString stringWithFormat:@"http://%@/ldcy/OrderGoods/OrderGoods.asmx/GetOrderDetails",str] pararms:dic
         success:^(id  _Nonnull json) {
            [SVProgressHUD dismiss];
            if ([[NSString stringWithFormat:@"%@",json[@"IsResult"]] isEqualToString:@"1"]) {
                NSArray *a = json[@"Data"];
                self.myTableViewArr = [a mutableCopy];
                [self.myTableView reloadData];
            }else{
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD setMinimumDismissTimeInterval:0.2f];
                [SVProgressHUD showImage:[UIImage imageNamed:@""] status:[NSString stringWithFormat:@"%@",json[@"Message"]]];
            }
        } fail:^(NSError * _Nonnull error) {
            NSData * data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
            NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"服务器的错误原因:%@",str);
            [SVProgressHUD dismiss];
        }];
    }
}
#pragma mark <UITableViewDelegate,UITableViewDataSource>
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.myTableViewArr.count;
//    return 10;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *idf = @"OrderHistoryInfoTableViewCell";
    ReviewOrderDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:idf];
    if (!cell) {
        cell = [[ReviewOrderDetailsTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:idf];
    }
    cell.dic = self.myTableViewArr[indexPath.row];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

@end
